<template>
  <div class="bg-color-white flex-center right-container" >
    <div class="flex-column-center" style="margin-top: 30px">
      <h2 class="password-title">设置密码</h2>
      <div style="margin: 20px 0">
        <el-steps style="width: 500px" :active="data.stepActive" align-center>
          <el-step title="验证身份"/>
          <el-step title="设置密码"/>
          <el-step title="完成"/>
        </el-steps>
      </div>
      <div v-if="data.stepActive == 1" class="step-container">
        <div class="mobile-container">手机号码：{{resetPasswordForm.mobile}}</div>
        <div style="margin-top: 35px">
          <el-form ref="checkMobileRef" :model="resetPasswordForm" :rules="rules">
            <div class="flex-start">
              <div>
                <el-form-item label="" prop="captcha">
                  <el-input v-model="resetPasswordForm.captcha" style="width: 260px" placeholder="请输入短信验证码"></el-input>
                </el-form-item>
              </div>
              <div style="margin-left: 7px;width: 123px;">
                <el-button :disabled="countdownVisible" class="footer-button" color="#04ADDB" style="font-size: 14px;font-weight: 400" @click="getResetCaptcha">{{countdownVisible? (countDown + '秒后可重新操作') : '获取短信验证码'}}</el-button>
              </div>
            </div>
          </el-form>
        </div>
        <div class="step-container">
          <el-button class="footer-button" :color="resetPasswordForm.captcha.length>5?'#04ADDB' : '#dddfe8'" style="color: #ffffff" @click="checkMobileHandle">{{'提交'}}</el-button>
        </div>
      </div>
      <div v-if="data.stepActive == 2" class="step-container">
        <div>
          <el-form ref="resetPasswordRef" :model="resetPasswordForm" :rules="rules">
            <el-form-item label="" prop="password">
              <el-input v-model="resetPasswordForm.password" style="width: 100%" type="password" placeholder="请输入新密码"></el-input>
            </el-form-item>
            <el-form-item label="" prop="againPassword">
              <el-input v-model="resetPasswordForm.againPassword" style="width: 100%" type="password" placeholder="请确认新密码"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="step-container">
          <el-button class="footer-button" :color="(resetPasswordForm.password == resetPasswordForm.againPassword && resetPasswordForm.againPassword)? '#04ADDB' : '#dddfe8'" style="color: #ffffff" @click="submitReset">{{'提交'}}</el-button>
        </div>
      </div>
      <div v-if="data.stepActive == 3" class="step-container">
        <div class="flex-all-center">
          <img style="width: 64px;height: 64px" src="@/assets/images/user/finish-icon.png" alt="">
          <div class="flex-column " style="margin-left: 30px">
            <div class="success-text-content">新密码设置成功！</div>
            <div class="tip-text-content">请牢记您的新密码，点击重新登录</div>
          </div>
        </div>
        <div class="step-container">
          <el-button class="footer-button" color="#04ADDB" @click="logoutHandle">{{'重新登录'}}</el-button>
        </div>
      </div>
    </div>
  </div>
  <captcha-dialog
      ref="captchaDialog"
    v-model:visible="captchaDialogVisible"
    @success="handleCaptchaSuccess"
  />
</template>

<script setup>
import {reactive, ref, getCurrentInstance, onMounted} from "vue";
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'
import {getCaptcha, postCaptcha, resetPassword} from '@/api/user.js'
import {validateMobile, validatePassword} from '@/utils/common.js'
import {checkMobile, logout} from '../../../api/user.js'
import {removeUserInfo} from '../../../utils/auth.js'
import CaptchaDialog from '../../component/captcha-dialog.vue'

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
const data = reactive({
  stepActive: 1,
  tempCaptchaParams: {}
})
let captchaDialogVisible = ref(false)
const resetPasswordForm = reactive({
  mobile: '',
  captcha: '',
  password: '',
  againPassword: '',
})
const countdownVisible = ref(false)
const countDown = ref(60)
const rules = ({
  mobile: [{ required: true, message: '请输入手机号码', trigger: 'blur' },{ validator: validateMobile, trigger: 'blur' }],
  captcha: [{ required: true, message: '请输入短信验证码', trigger: 'blur' }],
  password: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  againPassword: [{ required: true, message: '请输入确认密码', trigger: 'blur' },{ validator: validateRepeatPassword, trigger: 'blur' }],
})

onMounted(() => {
  initData()
})
let captchaDialog=ref()
// 图形验证码成功
const handleCaptchaSuccess = ({ imageCode, uuid }) => {
  const { mobile, sourceCode } = data.tempCaptchaParams;
  let dataForm = {
    sourceCode: sourceCode,
    mobile: mobile,
    code: imageCode,
    uuid: uuid
  };
  postCaptcha(dataForm).then((res) => {
        console.log('res:', res);
        if (res.code === 200) {
          ElMessage.success("操作成功，请留意手机短信");
          captchaDialogVisible.value = false;
          countdownVisible.value = true;
          let codeTime = 60;
          let codeSetInterval = setInterval(() => {
            codeTime--;
            countDown.value = codeTime;
            if (codeTime === 0) {
              clearInterval(codeSetInterval);
              countdownVisible.value = false;
              countDown.value = 60;
            }
          }, 1000);
        } else {
          ElMessage.error(res.msg);
          captchaDialog.value.refreshCode();
        }
      }
  );
}
const initData = () => {
  resetPasswordForm.mobile = localStorage.getItem('mobile')
}

function validateRepeatPassword(rule, value, callback) {
  if (!value || value === resetPasswordForm.password) {
    callback();
  } else {
    callback(new Error('与新密码不一致'));
  }
}

function getResetCaptcha() {
  // 先显示图形验证码弹窗
  captchaDialogVisible.value = true
  // 保存参数供验证后使用
  data.tempCaptchaParams = {
    sourceCode: 'updatePwdSource',
    mobile: resetPasswordForm.mobile,
  }
}
function checkMobileHandle() {
  proxy.$refs.checkMobileRef.validate((valid) => {
    if(valid){
      let dataForm = {
        mobile: resetPasswordForm.mobile,
        captchaCode: resetPasswordForm.captcha
      }
      checkMobile(dataForm, (res) => {
        ElMessage.success('校验成功')
        data.stepActive = 2
      })
    }
  })
}

function submitReset() {
  let dataForm = {
    mobile: resetPasswordForm.mobile,
    password: resetPasswordForm.password,
    againPassword: resetPasswordForm.againPassword
  }
  proxy.$refs.resetPasswordRef.validate((valid) => {
    if(valid){
      resetPassword(dataForm, (res) => {
        ElMessage.success('操作成功')
        data.stepActive = 3
      }, (err) => {
        ElMessage.error(err.msg)
      })
    }
  })
}
function logoutHandle() {
  logout({}, () => {
    goLogin('login')
    removeUserInfo()
  })
}

function goLogin(code) {
  router.push({
    path: '/login',
    query: {
      code: code
    }
  })
}

</script>
<style lang="scss" scoped>
.right-container {
  width: 1012px;
  padding-bottom: 30px
}
.password-title {
  font-size: 26px;
  font-weight: 400;
  text-align: center;
}
.step-container {
  margin-top: 35px;
  width: 390px
}
.mobile-container {
  width: 100%;
  font-size: 16px;
  color: #333333;
  font-weight: 400;
  text-align: left
}
.footer-button {
  width: 100%;
  height: 52px;
  border-radius: 2px;
  font-size: 16px;
  font-weight: 400;
  color: #ffffff
}
.success-text-content {
  font-size: 20px;
  font-weight: 500;
  color: #515151;
}
.tip-text-content {
  margin-top: 20px;
  font-size: 16px;
  font-weight: 400;
  color: #515151;
}
</style>
